<template>
  <div>
    <!-- 顶部导航栏 -->
    <a-card title="碳排放预测" bordered style="margin-bottom: 10px">
      <a-row>
        <a-col>
          <a-space>
            <a-button type="link" @click="goToHome">返回主页</a-button>
            <a-button type="link">数据分析</a-button>
            <a-button type="link">碳排放管理</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 预测类型选择 -->
    <a-card title="预测类型选择" bordered style="margin-bottom: 10px">
      <a-row :gutter="16">
        <a-col span="8">
          <a-form-item label="选择预测类型">
            <a-select
              v-model="selectedPredictionType"
              @change="updateChart"
              placeholder="请选择预测类型"
              style="width: 100%"
            >
              <a-select-option value="overall">园区整体</a-select-option>
              <a-select-option value="S1">S1</a-select-option>
              <a-select-option value="S2">S2</a-select-option>
              <a-select-option value="S3">S3</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-card>

    <!-- 预测曲线图 -->
    <a-card title="碳排放预测曲线图" bordered style="margin-bottom: 10px">
      <div style="height: 400px">
        <Echart :option="chartOptions" name="chartOptions" />
      </div>
    </a-card>

    <!-- 预测数据表格 -->
    <a-card title="碳排放预测数据表格" bordered>
      <a-table
        :dataSource="tableData"
        :columns="tableColumns"
        rowKey="time"
        style="margin-bottom: 10px"
        :pagination="pagination"
      />

      <a-space>
        <a-button type="primary" @click="exportToExcel">导出 Excel</a-button>
        <a-button type="primary" @click="exportToPDF">导出 PDF</a-button>
      </a-space>
    </a-card>
  </div>
</template>

<script setup>
import jsPDF from "jspdf";
import "jspdf-autotable"; // 直接扩展 jsPDF
import { computed, onMounted, reactive, ref } from "vue";
import { emissionprediction } from "/@/api/Carbon module/Carbon accounting module/Carbon prediction/emissionprediction";
import Echart from "/@/components/e-chart.vue"; // 确保路径正确
import { smartSentry } from "/@/lib/smart-sentry";
// 跳转到主页
const goToHome = () => {
  // 跳转逻辑
};

// 选择的预测类型
const selectedPredictionType = ref("overall");

// 模拟数据：曲线图和表格数据
const historicalData = ref([]);
const baselineData = ref([]);
const s1Data = ref([]);
const s2Data = ref([]);
const s3Data = ref([]);
const baselines1Data = ref([]);
const baselines2Data = ref([]);
const baselines3Data = ref([]);
// ECharts 配置选项
const chartOptions = computed(() => {
  return {
    title: { text: "碳排放预测曲线图", left: "center" },
    tooltip: { trigger: "axis" },
    legend: { data: ["历史碳排放", "基线预测", "S1", "S2", "S3"], top: "bottom" },
    xAxis: { type: "category", data: historicalData.value.map((d) => d.time) },
    yAxis: { type: "value", name: "碳排放量 (吨)" },
    series: [
      {
        name: "历史碳排放",
        type: "line",
        data: historicalData.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "基线预测",
        type: "line",
        data: baselineData.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S1历史碳排放量",
        type: "line",
        data: s1Data.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S1基线场景下的预测碳排放量",
        type: "line",
        data: baselines1Data.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S2历史碳排放量",
        type: "line",
        data: s2Data.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S2基线场景下的预测碳排放量",
        type: "line",
        data: baselines2Data.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S3历史碳排放量",
        type: "line",
        data: s3Data.value.map((d) => d.emissions),
        smooth: true,
      },
      {
        name: "S3基线场景下的预测碳排放量",
        type: "line",
        data: baselines3Data.value.map((d) => d.emissions),
        smooth: true,
      },
    ],
  };
});

// 表格数据
const tableData = ref([]);

// 表格列
const tableColumns = [
  { title: "时间（年月）", dataIndex: "timePeriod", key: "timePeriod" },
  {
    title: "园区历史碳排量",
    dataIndex: "historicalZemission",
    key: "historicalZemission",
    align: "center",
  },
  {
    title: "预测类型",
    dataIndex: "scope",
    key: "scope",
    align: "center",
  },
  {
    title: "预测时间段",
    dataIndex: "timePeriod",
    key: "timePeriod",
    align: "center",
  },
  {
    title: "园区历史碳排放量",
    dataIndex: "historicalZemission",
    key: "historicalZemission",
    align: "center",
  },
  {
    title: "园区基线场景下的预测碳排放量",
    dataIndex: "baselineZprediction",
    key: "baselineZprediction",
    align: "center",
  },
  {
    title: "S1历史碳排放量",
    dataIndex: "historicalS1emission",
    key: "historicalS1emission",
    align: "center",
  },
  {
    title: "S1基线场景下的预测碳排放量",
    dataIndex: "baselineS1prediction",
    key: "baselineS1prediction",
    align: "center",
  },
  {
    title: "S2历史碳排放量",
    dataIndex: "historicalS2emission",
    key: "historicalS2emission",
    align: "center",
  },
  {
    title: "S2基线场景下的预测碳排放量",
    dataIndex: "baselineS2prediction",
    key: "baselineS2prediction",
    align: "center",
  },
  {
    title: "S3历史碳排放量",
    dataIndex: "historicalS3emission",
    key: "historicalS3emission",
    align: "center",
  },
  {
    title: "S3基线场景下的预测碳排放量",
    dataIndex: "baselineS3prediction",
    key: "baselineS3prediction",
    align: "center",
  },
  {
    title: "基线预测碳排量",
    dataIndex: "baselineZprediction",
    key: "baselineZprediction",
    align: "center",
  },
];

// 导出功能
const exportToExcel = () => {
  // // 导出Excel逻辑
  // const workbook = new ExcelJS.Workbook();
  // // 添加工作表，名为sheet1
  // const sheet1 = workbook.addWorksheet("sheet1");
  // // 获取表头所有键
  // const headers = Object.keys(tableData.value[0]);
  // // 将标题写入第一行
  // sheet1.addRow(headers);
  // // 将数据写入工作表
  // tableData.value.forEach((row) => {
  //   const values = Object.values(row);
  //   sheet1.addRow(values);
  // });
  // // 导出表格文件
  // workbook.xlsx
  //   .writeBuffer()
  //   .then((buffer) => {
  //     let file = new Blob([buffer], { type: "application/octet-stream" });
  //     FileSaver.saveAs(file, "ExcelJS.xlsx");
  //   })
  //   .catch((error) => console.log("Error", error));

  const headers = [
    "时间（年月）",
    "园区历史碳排量",
    "预测类型",
    "预测时间段",
    "园区历史碳排放量",
    "园区基线场景下的预测碳排放量",
    "S1历史碳排放量",
    "S1基线场景下的预测碳排放量",
    "S2历史碳排放量",
    "S2基线场景下的预测碳排放量",
    "S3历史碳排放量",
    "S3基线场景下的预测碳排放量",
    "基线预测碳排量",
  ];

  // 将表头转换为 Excel 的 XML 格式
  const headerRow = headers
    .map((header) => `<Cell><Data ss:Type="String">${header}</Data></Cell>`)
    .join("");
  const headerXml = `<Row>${headerRow}</Row>`;
  // 将数据转换为 Excel 的 XML 格式
  const rowsXml = tableData.value
    .map((row) => {
      const cells = [
        row.timePeriod || "",
        row.historicalZemission || "",
        row.scope || "",
        row.timePeriod || "",
        row.historicalZemission || "",
        row.baselineZprediction || "",
        row.historicalS1emission || "",
        row.baselineS1prediction || "",
        row.historicalS2emission || "",
        row.baselineS2prediction || "",
        row.historicalS3emission || "",
        row.baselineS3prediction || "",
        row.baselineZprediction || "",
      ]
        .map((value) => `<Cell><Data ss:Type="String">${value}</Data></Cell>`)
        .join("");

      return `<Row>${cells}</Row>`;
    })
    .join("");

  // 完整的 XML 文件内容
  const xmlContent = `
    <?xml version="1.0"?>
    <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
              xmlns:o="urn:schemas-microsoft-com:office:office"
              xmlns:x="urn:schemas-microsoft-com:office:excel"
              xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
      <Styles>
        <Style ss:ID="Default" ss:Name="Normal">
          <Alignment ss:Vertical="Center" />
          <Borders />
          <Font ss:FontName="Calibri" ss:Size="11" ss:Color="#000000" />
          <Interior />
          <NumberFormat />
          <Protection />
        </Style>
      </Styles>
      <Worksheet ss:Name="Sheet1">
        <Table>
          ${headerXml}
          ${rowsXml}
        </Table>
      </Worksheet>
    </Workbook>
  `;
  // 创建 Blob 对象并下载
  const blob = new Blob([xmlContent], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "碳排放预测数据.xlsx";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

const exportToPDF = () => {
  // 导出PDF逻辑
  const doc = new jsPDF();

  // 设置 PDF 标题
  doc.setFontSize(16);
  doc.text("碳排放预测数据", 14, 20);
  // 表格头部
  const headers = [
    [
      "时间（年月）",
      "园区历史碳排量",
      "预测类型",
      "预测时间段",
      "园区历史碳排放量",
      "园区基线场景下的预测碳排放量",
      "S1历史碳排放量",
      "S1基线场景下的预测碳排放量",
      "S2历史碳排放量",
      "S2基线场景下的预测碳排放量",
      "S3历史碳排放量",
      "S3基线场景下的预测碳排放量",
      "基线预测碳排量",
    ],
  ];
  // 提取数据
  const rows = tableData.value.map((row) => [
    row.timePeriod || "",
    row.historicalZemission || "",
    row.scope || "",
    row.timePeriod || "",
    row.historicalZemission || "",
    row.baselineZprediction || "",
    row.historicalS1emission || "",
    row.baselineS1prediction || "",
    row.historicalS2emission || "",
    row.baselineS2prediction || "",
    row.historicalS3emission || "",
    row.baselineS3prediction || "",
    row.baselineZprediction || "",
  ]);

  // 使用 jsPDF 的 autoTable 插件生成表格
  doc.autoTable({
    startY: 30, // 表格起始位置
    head: headers,
    body: rows,
    styles: {
      font: "helvetica",
      fontSize: 10,
      cellPadding: 3,
      overflow: "linebreak",
    },
    headStyles: {
      fillColor: [22, 160, 133], // 表头背景颜色
      textColor: 255, // 表头字体颜色
      fontStyle: "bold",
    },
    alternateRowStyles: { fillColor: [240, 240, 240] }, // 表格条纹背景色
  });

  // 导出 PDF
  doc.save("碳排放预测数据.pdf");
};

// 更新图表
const updateChart = () => {
  // 依据 selectedPredictionType 更新图表的逻辑
  console.log("碳排放量对比");
};

// 查询数据
const pagination = computed(() => ({
  total: total.value,
  current: queryFormState.pageNum,
  pageSize: queryFormState.pageSize,
}));
const total = ref(0); //总数
const queryFormState = {
  pageNum: 1,
  pageSize: 10,
};
const queryForm = reactive({ ...queryFormState });
async function queryData() {
  try {
    let queryResult = await emissionprediction.query(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
    historicalData.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.historicalZemission,
    }));
    baselineData.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.baselineZprediction,
    }));
    s1Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.historicalS1emission,
    }));
    s2Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.historicalS2emission,
    }));
    s3Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.historicalS3emission,
    }));
    baselines1Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.baselineS1prediction,
    }));
    baselines2Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.baselineS2prediction,
    }));
    baselines3Data.value = tableData.value.map((item) => ({
      time: item.timePeriod,
      emissions: item.baselineS3prediction,
    }));
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}

onMounted(() => {
  queryData();
});
</script>

<style scoped>
a-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

a-button {
  margin-top: 16px;
}

h2 {
  color: #1890ff;
  font-weight: bold;
}
</style>
